package com.zero.common.datasource;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

public class DataSourceAdvice implements MethodBeforeAdvice,
		AfterReturningAdvice, ThrowsAdvice {
	// service方法执行之前被调用
	public void before(Method method, Object[] args, Object target)
			throws Throwable {
		if (method.getName().startsWith("save")
				|| method.getName().startsWith("update")
				|| method.getName().startsWith("delete")
				|| method.getName().startsWith("execute") ) {
			DataSourceSwitcher.setMaster();
		} else {
			DataSourceSwitcher.setSlave();
		}
	}

	// service方法执行完之后被调用
	public void afterReturning(Object arg0, Method method, Object[] args,
			Object target) throws Throwable {
	}

	// 抛出Exception之后被调用
	public void afterThrowing(Method method, Object[] args, Object target,
			Exception ex) throws Throwable {
		DataSourceSwitcher.setSlave();
	}

}